package com.weitu.securitycheck.controller;

import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.contractor.entity.ContractorAudit;
import com.weitu.contractor.service.ContractorAuditService;
import com.weitu.paging.DataGridPagination;
import com.weitu.plugin.PageView;
import com.weitu.securitycheck.entity.CheckProblem;
import com.weitu.securitycheck.entity.CheckProblemCriteria;
import com.weitu.securitycheck.service.CheckProblemService;
import com.weitu.task.entity.Task;
import com.weitu.task.service.TaskService;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/5/18
 */
@Controller
@RequestMapping(value = "securityCheck/checkProblem")
public class CheckProblemController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "securityCheck/checkProblem";
    private final CheckProblemService checkProblemService;
    private final ContractorAuditService contractorAuditService;
    private final TaskService taskService;

    @Autowired
    public CheckProblemController(CheckProblemService checkProblemService
            , ContractorAuditService contractorAuditService
            , TaskService taskService) {
        this.checkProblemService = checkProblemService;
        this.contractorAuditService = contractorAuditService;
        this.taskService = taskService;
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add() throws Exception {
        return MODULE_BATH_PATH + "/add";
    }

    @RequestMapping(value = "edit", method = RequestMethod.GET)
    public String edit(Model model, @RequestParam("id") String id) throws Exception {
        CheckProblem checkProblem = checkProblemService.selectByPrimaryKey(id);
        if (checkProblem.getContractorAuditId() != null) {
            ContractorAudit contractorAudit = contractorAuditService.selectByPrimaryKey(checkProblem.getContractorAuditId());
            model.addAttribute("contractorId", contractorAudit.getContractorId());
        }

        model.addAttribute(checkProblem);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "view", method = RequestMethod.GET)
    public String view(Model model, @RequestParam("id") String id) throws Exception {
        CheckProblem checkProblem = checkProblemService.selectByPrimaryKey(id);
        if (checkProblem.getContractorAuditId() != null) {
            ContractorAudit contractorAudit = contractorAuditService.selectByPrimaryKey(checkProblem.getContractorAuditId());
            model.addAttribute("contractorId", contractorAudit.getContractorId());
        }

        model.addAttribute(checkProblem);
        return MODULE_BATH_PATH + "/view";
    }

    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request) throws Exception {
        CheckProblemCriteria criteria = new CheckProblemCriteria();
        CheckProblemCriteria.Criteria cr = criteria.createCriteria()
                .andDelStateEqualTo(0)
                .andCheckInfoIdEqualTo(getPara("checkInfoId"));

        int count = checkProblemService.countByCriteria(criteria);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(getPara("sort"))) {
            pageView.setSortColumn("addTime");
        } else {
            criteria.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        criteria.setPageView(pageView);

        List<CheckProblem> checkProblems = checkProblemService.selectByCriteria(criteria);

        return dataGridPagination.flushDataGridData(checkProblems);
    }

    @SystemLog(module = "检查问题", methods = "新增检查问题信息")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult addAjax(CheckProblem checkProblem) throws Exception {
        String id = IDGenerator.getId();
        checkProblem.setId(id);
        checkProblem.setAddUserId(getSessionUser().getId());
        checkProblem.setAddDeptId(getSessionUser().getDepartment().getId());
        checkProblem.setAddTime(DateTimeUtil.formatterDateTime());
        // TODO: 2017/5/23 思考下发任务的时机
        insertRectifyInfo(checkProblem);
        if (checkProblemService.saveAccessoryAndInsert(checkProblem)) {
            return success("保存成功！", checkProblem);
        }
        return fail("保存失败！");
    }

    @SystemLog(module = "检查问题", methods = "编辑检查问题信息")
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public AjaxResult editAjax(CheckProblem checkProblem) throws Exception {
        checkProblem.setUpdateUserId(getSessionUser().getId());
        checkProblem.setUpdateDeptId(getSessionUser().getDepartment().getId());
        checkProblem.setUpdateTime(DateTimeUtil.formatterDateTime());
        if (checkProblemService.saveAccessoryAndUpdate(checkProblem)) {
            return success("保存成功！", checkProblem);
        }
        return fail("保存失败！");
    }

    @SystemLog(module = "检查问题", methods = "删除检查问题信息")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteAjax(String id) throws Exception {
        if (checkProblemService.deleteByPrimaryKey(id) > 0) {
            return success("删除成功！");
        } else {
            return fail("删除失败！");
        }
    }

    /**
     * 添加整改下发信息
     *
     * @param checkProblem 参数
     */
    private void insertRectifyInfo(CheckProblem checkProblem) {
        int rectifyType = checkProblem.getRectifyType();
        int isCheckContractor = checkProblem.getIsCheckContractor();
        if (rectifyType == 1 && isCheckContractor == 1) {//立即整改
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", IDGenerator.getId());
            map.put("taskId", checkProblem.getId());
            map.put("taskSource", "安全检查-检查信息-检查问题");
            map.put("taskName", "安全检查问题整改");
            map.put("taskDescribe", checkProblem.getRectifyRemarks());
            map.put("receiveUserId", checkProblem.getRectifyUserId());
            map.put("requireTime", DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));
            map.put("acceptUserId", getSessionUser().getId());
            taskService.insertSelective(map);
        }
    }

    /**
     * 更新整改下发信息
     *
     * @param checkProblem 参数
     */
    private void updateRectifyInfo(CheckProblem checkProblem) {
        int rectifyType = checkProblem.getRectifyType();
        int isCheckContractor = checkProblem.getIsCheckContractor();
        if (rectifyType == 1 && isCheckContractor == 1) {//立即整改
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("taskId", checkProblem.getId());
            List<Task> tasks = taskService.selectByTaskId(paramMap);
            if (tasks.size() > 0) {
                String id = tasks.get(0).getId();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("taskId", checkProblem.getId());
                map.put("taskSource", "安全检查-检查信息-检查问题");
                map.put("taskName", "安全检查问题整改");
                map.put("taskDescribe", checkProblem.getRectifyRemarks());
                map.put("receiveUserId", checkProblem.getRectifyUserId());
                map.put("requireTime", DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));
                map.put("acceptUserId", getSessionUser().getId());
                taskService.updateById(map);
            }
        }
    }
}
